/**
 * Parser class
 * 
 * Provides methods to interpret DekaruMath commands.
 * 
 * @author David Alvarez November, 6, 2006
 */
package com.dekaru.math;

import java.io.*;
import java.util.*;

import com.dekaru.util.PrintReader;
import com.dekaru.math.type.Matrix;

public class Parser {

	private static final String ERROR = "unknown input syntax";
	
	public static Object parseFile(PrintReader pr) {
		
		try {
			if (pr.readLinef().equalsIgnoreCase("enter matrix")) { return readMatrix(pr); }
		} catch(IOException ioe) {
			return ioe.toString();
		}

    	return ERROR;
	}
	
	public static Object executeCommand(PrintReader pr, String cmd) {
		
		if (cmd.equalsIgnoreCase("enter matrix")) { return readMatrix(pr); }
		
		return ERROR;
	}
	
	public static Object readMatrix(PrintReader pr) {
		
		Vector<Vector> rows = new Vector<Vector>();
		try {
			String s = pr.readLinef();
			while (!s.equals(".")) {
				Vector<Double> cols = new Vector<Double>();
    			StringTokenizer stk = new StringTokenizer(s, " ");
    			while (stk.hasMoreTokens()) {
					cols.add(Double.parseDouble((stk.nextToken())));
    			}
    			rows.add(cols);
    			s = pr.readLinef();
			}
			return new Matrix(rows);
		} catch(NumberFormatException nfe) {
			return nfe.toString();
		} catch(IOException ioe) {
			return ioe.toString();
		} catch(NullPointerException npe) {
			return new Matrix(rows);
		}
	}
}
